/*
 * @Author: Naohand 120262455+Naohand@users.noreply.github.commtx
 * @Date: 2023-04-07 10:14:38
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-09-30 21:58:11
 * @FilePath: commSerial.cpp
 * @Description:
 */
#include <mcu_pack/commSerial.hpp>

commSerial::commSerial(const char* port, uint32_t baudrat)
{
    std::cout << "1\n";
    this_port = port;
    this_baudrate = baudrat;
}

commSerial::~commSerial()
{
}
void commSerial::commSerialInit()
{
#ifdef UARTCOM
    handle = open(this_port, O_RDWR | O_NOCTTY | O_NDELAY);
    std::cout << "handle:" << handle << std::endl;

    while (handle == -1)
    {
        handle = open(this_port, O_RDWR | O_NOCTTY | O_NDELAY);
        perror("open_port: Unable to open serial\n");
        std::cout << "handle = " << handle << std::endl;
    }
    tcgetattr(handle, &termAttr);
    cfsetispeed(&termAttr, this_baudrate);
    cfsetospeed(&termAttr, this_baudrate);
    termAttr.c_cflag &= ~PARENB;
    termAttr.c_cflag &= ~CSTOPB;
    termAttr.c_cflag &= ~CSIZE;
    termAttr.c_cflag |= CS8;
    termAttr.c_cflag |= (CLOCAL | CREAD);
    termAttr.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    termAttr.c_iflag &= ~(IXON | IXOFF | IXANY);
    termAttr.c_oflag &= ~OPOST;
    termAttr.c_cc[VMIN] = 0;
    termAttr.c_cc[VTIME] = 1;
    tcflush(handle, TCIOFLUSH);
    tcsetattr(handle, TCSANOW, &termAttr);
    std::cout << "serial configured....\n";
#endif
}
int commSerial::commSerialIsopen()
{
    return (ifSerial);
}
int commSerial::commSerialRead()
{
#ifdef UARTCOM
    int MCU_len = 0;
    MCU_len = read(handle, rxbuf, RX_DATA_LEN);
    std::cout << "MCU_len:" << MCU_len << std::endl;
    return MCU_len;
#endif
}

void commSerial::commSerialWrite(char *data)
{
    int len2 = write(handle, data, TX_DATA_LEN);
    std::cout << "len2:" << len2 << std::endl;
}